package com.dd.common.utils;

import java.math.BigInteger;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.stream.IntStream;

/**
 * 生成短id
 *
 */
public class ShortIdWorker {

    /**
     * 初始时间限定为2024-03-01 00:00:00
     */
    private final static long START_STAMP = 1690819200000L;

    /**
     * 容错因子
     */
    private final static int FAULT_TOLERANCE_FACTOR = 10;

    /**
     * 默认长度
     */
    private final static int DEFAULT_ID_LENGTH = 12;

    /**
     * 数据库每毫秒可保存的数据，结合列的数量取值，建议实测后更改
     */
    private final static int DEFAULT_TRANSFER_SPEED_PER_MILLISECOND = 50;

    private final int length;

    private final int transferSpeedPerMillisecond;

    /**
     * 上次运行时间
     */
    private long lastStamp = -1L;

    /**
     * 增长序列
     */
    private int seqNum;

    private static ShortIdWorker instance;

    /**
     * 单例模式
     */
    public static ShortIdWorker getInstance() {
        if (null == instance) {
            instance = new ShortIdWorker();
        }
        return instance;
    }

    public static ShortIdWorker newInstance(int length, int transferSpeedPerMillisecond) {
        return new ShortIdWorker(length, transferSpeedPerMillisecond);
    }

    /**
     * 默认使用12位id，数据库每毫秒新增数据为50条
     */
    private ShortIdWorker() {
        this(DEFAULT_ID_LENGTH, DEFAULT_TRANSFER_SPEED_PER_MILLISECOND);
    }

    private ShortIdWorker(int length, int transferSpeedPerMillisecond) {
        this.length = length;
        this.transferSpeedPerMillisecond = transferSpeedPerMillisecond;
    }

    /**
     * @return 生成后的id
     * <p>
     * 例：757b12c001d3
     * 共length位id,前x位为时间戳差值的16进制,后y位为不固定步长的自增序列
     */
    public synchronized String nextId() {

        long now = now();
        // 获取16进制时间戳前缀
        String stampPrefix = getStampStr(now);
        // 获取第二段增长序列的长度l2
        int l2 = this.length - stampPrefix.length();
        // 获取l2位16进制的最大值
        int max = IntStream.range(0, l2).map(i -> 16).reduce(1, (a, b) -> a * b) - 1;
        // 获取增长的平均步长averageStepLength
        int averageStepLength = max / this.transferSpeedPerMillisecond;
        // 取步长范围
        // averageStepLength的平均值是averageStepLength/2,累加的情况下会有后一半的空间浪费问题，故取值为averageStepLength*2,平均值为averageStepLength
        // 取随机数的结果不可控，上行中列举的只是近似值，为防止多次溢出影响程序执行时间，再减去容错因子，减小溢出概率（容错因子建议在本地系统实测后更改）
        int randomStepLengthMax = (averageStepLength << 1) - (averageStepLength / FAULT_TOLERANCE_FACTOR);
        // 在步长范围内获取随机步长
        int randomStepLength = new Random().nextInt(randomStepLengthMax) + 1;
        // 当上次运行时间小于当前时间或第一次运行时，增长序列赋值为随机步长，设置最后运行时间
        if (this.lastStamp < now || this.lastStamp == -1L) {
            this.seqNum = randomStepLength;
            this.lastStamp = now;
            // 当上次运行时间与当前运行时间处于同一毫秒时
        } else if (this.lastStamp == now) {
            // 增长序列以随机步长为步长递增
            this.seqNum += randomStepLength;
            // 当增长序列大于最大值时
            if (this.seqNum > max) {
                // 程序暂停一毫秒
                LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1));
                // 重新获取前缀，增长序列重新开始
                this.seqNum = randomStepLength;
                Long newNow = now();
                this.lastStamp = newNow;
                stampPrefix = getStampStr(newNow);
            }
        } else {
            // 时钟回拨，报错
            throw new IllegalStateException("Clock moved backwards.  Reject to generate id");
        }
        // 将增长序列转为16进制与时间戳拼接
        return stampPrefix + String.format("%0" + l2 + "X", new BigInteger(String.valueOf(this.seqNum), 10));
    }


    private  static String hex10To16(String str) {
        return String.format("%X", new BigInteger(str, 10));
    }

    private long now() {
        return System.currentTimeMillis();
    }

    /**
     * 获取传入时间与开始时间的间隔毫秒数，将结果转为16进制
     * @param now 时间戳
     * @return
     */
    private   String getStampStr(Long now) {
        return hex10To16(String.valueOf(now - START_STAMP));
    }




}